package com.example.api.mall.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @name: LoginFilter
 * @description: 检测是否登录  过滤器是基于servlet的，所有获取的是原始的请求
 * @author: xw.s
 * @date: 2021/5/31-15:54
 */
@Slf4j
@WebFilter(urlPatterns = {"/*"}, filterName = "logFilter") //过滤所有的请求 /*  两个星号/**不行^_^
@Order(2)  //应该是过滤器执行的顺序
public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("登录验证过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("登录验证过滤器开始执行");
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("URL : " + req.getRequestURL());
        log.info("URI : " + req.getRequestURI());
        if (!"aaa".equals(req.getRequestURI())){
            //这个异常只是被抛出，不会被统一异常处理捕获，并且后面的拦截器还是会正常执行，但是执行结果有问题。
//            throw new SystemException("这是过滤器发出的异常");
        }
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {
        log.info("destroy登录验证过滤器");
    }
}
